package database

import (
	"common/config"
	"common/logs"
	"log"
	"os"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type MysqlManager struct {
	GOrm *gorm.DB
}

// DB 数据库连接实例

// Connect 初始化数据库连接
func NewMysql() *MysqlManager {
	cfg := config.Conf.Mysql["gogame"]
	dsn := cfg.User + ":" + cfg.Password + "@tcp(" + cfg.Host + ")/" + cfg.DBName + "?charset=utf8mb4&parseTime=True&loc=Local"
	logs.Error("dsn:", dsn)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{
			// 日志级别，可设置为 logger.Silent、logger.Error、logger.Warn、logger.Info
			LogLevel: logger.Info,
			// 是否使用彩色输出
			Colorful: true,
		}),
	})
	logs.Error("err", err)
	if err != nil {
		logs.Fatal("Could not connect to the Mysql ", err)
		return nil
	}
	err = db.Exec("SELECT 1").Error
	if err != nil {
		logs.Error("Connection Mysql failed:", err)
		return nil
	} else {
		logs.Info("Connection test succeeded")
	}
	return &MysqlManager{
		GOrm: db,
	}
}
